문서의 임의 삭제는 제재 대상으로, 문서를 삭제하려면 삭제 토론을 진행해야 합니다. 문서 보기문서 삭제토론 프로그래밍 언어/예제 (문단 편집) === [[Python]] === {{{#!syntax python for i in range(99, -1, -1): if i == 0: print("No more bottles of beer on the wall, no more bottles of beer. ") print("Go to the store and buy some more, 99 bottles of beer on the wall.") elif i == 1: print("1 bottle of beer on the wall, 1 bottle of beer. ") print("Take one down and pass it around, no more bottles of beer on the wall. ") else: print("{0} bottles of beer on the wall, {0} bottles of beer. ".format(i)) print("Take one down and pass it around, ", (i - 1), "bottles of beer on the wall. ") }}} 또는 {{{#!syntax python start = 99 def bottles(i, leading): if i < 0: i = start _n = "N" if leading else "n" _s = "s" if i != 1 else "" _i = str(i) if i != 0 else _n + "o more" return _i + " bottle" + _s take_or_buy = lambda i: "Go to the store and buy some more" if i == 0 else "Take one down and pass it around" for i in range(start, -1, -1): print(bottles(i, True) + " of beer on the wall, " + bottles(i, False) + " of beer.") print(take_or_buy(i) + ", " + bottles(i - 1, False) + " of beer on the wall.") print("") }}} 여기서 사용된 함수 중 행 첫머리 여부에 따른 대소문자 지정 등으로 비교적 복잡한 bottles(i, leading)은 일반적인 함수선언인 def문으로, 그보다 간단한 take_or_buy(i)는 lambda문으로 쓰여 있다. 곳곳에 보이는 A if B else C 문은 삼항연산자로, B의 값에 따라 True이면 A, False이면 C가 된다. C 스타일로 쓰면 B?A:C에 해당한다. 13행에서 보다시피 range문은 argument를 세 개 먹는데, 이를 이용해 C 스타일 for문을 range문으로 바꿀 수 있다. 또는 파이썬 3.10의 match 문법을 사용한 버전. {{{#!syntax python from textwrap import dedent def to_bottles(n: int) -> str: match n: case 0: return "no more bottles" case 1: return "1 bottle" case _: return f"{n} bottles" def get_verse(n: int) -> str: match n: case 0: return dedent( f"""\ {to_bottles(n).capitalize()} of beer on the wall, {to_bottles(n)} of beer. Go to the store and buy some more, {to_bottles(99)} of beer on the wall. """ ) case _: return dedent( f"""\ {to_bottles(n)} of beer on the wall, {to_bottles(n)} of beer. Take one down and pass it around, {to_bottles(n - 1)} of beer on the wall. """ ) if __name__ == "__main__": for i in range(99, -1, -1): print(get_verse(i)) }}}저장 버튼을 클릭하면 당신이 기여한 내용을 CC-BY-NC-SA 2.0 KR으로 배포하고,기여한 문서에 대한 하이퍼링크나 URL을 이용하여 저작자 표시를 하는 것으로 충분하다는 데 동의하는 것입니다.이 동의는 철회할 수 없습니다.캡챠저장미리보기